package com.hulman.oms.web;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.Vehicle;
import com.hulman.oms.service.VehicleService;
import com.hulman.oms.util.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@RestController
public class VehicleController
{
    @Autowired
    private VehicleService vehicleService;

    @Autowired
    private HttpServletResponse response;

    @GetMapping("/vehicles/{id}")
    public Result findVehicleById(@PathVariable Integer id)
    {
        Vehicle vehicle = vehicleService.findVehicleById(id);
        return new Result(vehicle);
    }

    @GetMapping("/vehicles")
    public Result findVehicles(Integer page, Integer limit, String name, String type, Integer state)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        map.put("name", name);
        map.put("type", type);
        map.put("state", state);
        return vehicleService.findVehiclesResult(map);
    }

    @DeleteMapping("/vehicles/{ids}")
    public Result deleteVehicleById(@PathVariable String ids)
    {
        int[] idArrays = NumberUtil.parseIntArray(ids);
        for (Integer id : idArrays)
        {
            vehicleService.deleteVehicleById(id);
        }
        return Result.SUCCESS;
    }

    @PutMapping("/vehicles")
    public Result saveVehicle(Vehicle vehicle)
    {
        vehicleService.saveVehicle(vehicle);
        return Result.SUCCESS;
    }

    /**
     * 通过Excel批量导入车辆信息
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/vehicles/import")
    public Result importVehicles(MultipartFile file) throws IOException
    {
        File tmp = new File(System.getProperty("java.io.tmpdir") + "/" + System.currentTimeMillis() + ".xlsx");
        file.transferTo(tmp);
        try
        {
            List<Vehicle> vehicles = EasyExcel.read(tmp).head(Vehicle.class).sheet(0).doReadSync();
            for (Vehicle vehicle : vehicles)
            {
                vehicle.setState(1);
                vehicleService.saveVehicle(vehicle);
            }
            return Result.SUCCESS;
        } catch (Exception ex)
        {
            ex.printStackTrace();
            return new Result(ex.getMessage(), null);
        }
    }

    /**
     * 导出车辆列表
     *
     * @throws IOException
     */
    @GetMapping("/vehicles/export")
    public void exportVehicles() throws IOException
    {
        String fileName = "车辆清单.xlsx";
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        List<Vehicle> vehicles = vehicleService.findVehicles(new HashMap<>());
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet sheet0 = EasyExcel.writerSheet(0, "车辆").head(Vehicle.class).build();
        excelWriter.write(vehicles, sheet0);
        excelWriter.finish();
    }

}
